package org.example.controller;

import org.example.service.HrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


@Controller
public class HrController {


    @Autowired
    private HrService hrService;


    @RequestMapping("loginView")
    public ModelAndView welcome(ModelAndView mv, HttpServletRequest request) {
        request.getSession().removeAttribute("username");
        mv.setViewName("login");
        return mv;
    }

    @RequestMapping("uploadView")
    public ModelAndView uploadView(ModelAndView mv) {
        mv.setViewName("upload");
        return mv;
    }


    @PostMapping("login")
    public String login(String username, String password, HttpServletRequest request) {
        if (null == username || null == password) {
            return "用户名或密码为空，请重新输入";
        } else {
            if (hrService.login(username, password)) {
                request.getSession().setAttribute("username", username);
                return "forward:welcomeView";
            } else {
                return "未查询到该用户";
            }
        }
    }

    @PostMapping("upload")
    @ResponseBody
    public String upload(MultipartFile[] upFile) throws IOException {
        for (MultipartFile file : upFile) {
            // 上传文件的名字
            String filename = file.getOriginalFilename();

            // 文件重命名，防止重名导致覆盖
            filename = UUID.randomUUID() + "_" + filename;

            file.transferTo(new File("e:/" + filename));
        }
        return "upload success!";
    }

}
